package com.kgc.activiti.util;

import java.io.*;

public class FileUtil {
    /**
     * 读文本文件
     *
     * @param sourcePath 读取文件路径
     * @param charset    指定字符编码格式
     * @return
     */
    public static String read(String sourcePath, String charset) {
        BufferedReader br = null;
        StringBuffer strb = new StringBuffer();
        try {
            br = new BufferedReader(new InputStreamReader(new FileInputStream(sourcePath), charset));
            String lineStr;// 每一行的内容
            while ((lineStr = br.readLine()) != null) {
                strb.append(lineStr).append("\n");
            }
        } catch (UnsupportedEncodingException | FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null) {// 不为空则关闭资源
                    br.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return strb.toString();// 返回拼接之后的字符串
    }

    /**
     * 写文本文件
     *
     * @param content    写的内容
     * @param targetPath 写入路径
     * @param charset    指定字符集
     */
    public static void write(String content, String targetPath, String charset) {
        BufferedWriter bw = null;
        try {
            bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(targetPath), charset));
            bw.write(content);
            bw.flush();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bw != null) {
                    bw.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
